<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{total}} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="openDrawer('add')"
            round>
            添加面经
          </el-button>
        </div>

      </template>
      <!--
        el-table
        data => 放数据 [{},{},{}]
        prop 对象里面的属性名 键名
       -->
      <template #default>
        <el-table :data="list" style="width: 100%">
          <el-table-column fixed prop="stem" label="标题" width="400">
          </el-table-column>
          <el-table-column prop="creator" label="作者"> </el-table-column>
          <el-table-column prop="likeCount" label="点赞"> </el-table-column>
          <el-table-column prop="views" label="浏览数"> </el-table-column>
          <el-table-column prop="createdAt" label="更新时间" width="200">
          </el-table-column>
          <!-- 自定义列的模板，其实就是一个作用域插槽 -->
          <el-table-column label="操作">
            <!--
              obj.row 对应的就是数组中的每一个item
              obj.$index => 下标 一般不怎么用
             -->
            <template #default=" { row }">
              <!-- {{ obj.row }} -->
              <!-- {{ column }} -->
              <!-- {{ $index }} -->
                <div class="actions">
                  <i class="el-icon-view" @click="openDrawer('view', row.id)"></i>
                  <i class="el-icon-edit-outline" @click="openDrawer('edit', row.id)"></i>
                  <i class="el-icon-delete" @click="handleDel(row.id)"></i>
              </div>
            </template>
          </el-table-column>
      </el-table>
      </template>
    </el-card>
    <!-- 分页功能 -->
    <el-pagination
      background
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-size="pageSize"
      layout="prev, pager, next"
      :total="total">
    </el-pagination>
    <!--
      current : 当前显示的是哪一页
      size-change : 每页显示多少条变化的时候触发
      current-change： 页码变化的时候触发
      page-size：当前生效的每页多少条
      total :  数据的总量

      layout : 底部要展示哪些
     -->

     <!--
       rtl  ==> right to left  从右到左展开
       visible ==> 是否显示
      -->
     <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      direction="rtl"
      size="50%"
      :before-close="handleClose">
      <!-- 这里放内容 -->
      <!--
        :model => 绑定form对象
        :rules  ==> 校验的规则
        prop  ==> 对应规则的key
        v-model  ==> 给对应的表单元素绑定
       -->
       <div v-if="drawerType === 'view'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <!-- 插值表达式不解析html标签， -->
        <div v-html="form.content"></div>
      </div>
      <el-form v-else :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 它不是element-ui提供给我们的组件，trigger ==> blur 触发不了 -->
          <!-- 自定义一个blur事件 -->
          <quill-editor v-model="form.content" @blur="handleBlur"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
    </el-form>
    </el-drawer>

  </div>

</template>
<!--
  插槽的分类
  1. 默认插槽
  2. 具名插槽
  3. 作用域插槽

  el-table-coloum  ==> 大致是这个样子的
   作用域插槽，传值，放到slot标签上，以属性的形式
<div v-for="(item, index) in data">
    <slot name="default" :row="item" :$index="index"></slot>
 </div>
 -->

<script>
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
import '@pnpm/quill/dist/quill.core.css'
import '@pnpm/quill/dist/quill.snow.css'
import '@pnpm/quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { createArticle, getArticleDetail, getArticleList, removeArticle, updateArticle } from '@/api/article'
export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      list: [], // 渲染表格的list
      current: 1, // 当前获取的是第几页
      pageSize: 5, // 每页显示多少条
      total: 0, // 总条数
      drawer: false,
      drawerType: 'add',
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '请输入面经标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  computed: {
    drawerTitle () {
      // 根据drawerType 不同，得到不同的title值
      if (this.drawerType === 'add') return '添加面经'
      if (this.drawerType === 'view') return '预览面经'
      if (this.drawerType === 'edit') return '编辑面经'
      return '我是默认的哟~'
    }
  },
  created () {
    this.initData()
  },
  methods: {
    async initData () {
      const { data } = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      this.list = data.rows
      this.total = data.total
    },
    async handleDel (id) {
      console.log(id)
      await removeArticle(id)
      // 删除成功
      this.$message.success('删除成功')
      // 渲染
      this.initData()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.current = val
      this.initData()
    },
    async openDrawer (type, id) {
      // add view  edit  ==> 表示我点击的哪一个按钮打开的
      this.drawerType = type
      this.drawer = true

      // type只要是不add，都要获取数据  view edit
      if (type !== 'add') {
        const res = await getArticleDetail(id)
        console.log(res)
        // 将res.data对象展开，都放到form对象中
        this.form = {
          ...res.data
        }
      }
    },
    handleClose () {
      // 预览的时候关闭，resetFields报错，因为没有表单
      // 我们手动重置一下，不然会影响到 add 添加的时候，会带有数据
      // 每次关的时候，清空
      this.form = { stem: '', content: '' }
      // add view edit
      if (this.drawerType !== 'view') {
        this.$refs.form.resetFields()
      }

      this.drawer = false
    },
    // 对content单独进行校验
    handleBlur () {
      this.$refs.form.validateField('content')
    },
    // 提交表单，向后端发送请求
    async submitForm () {
      try {
        // 1. 校验表单
        await this.$refs.form.validate()

        // 如果点击的是添加
        if (this.drawerType === 'add') {
        // 发送请求
          await createArticle(this.form)
          // 添加成功的提示
          this.$message.success('添加成功哟~')
        }
        // 如果点击的是修改
        if (this.drawerType === 'edit') {
          const { id, stem, content } = this.form
          await updateArticle({ id, stem, content })
          this.$message.success('更新成功~')
        }

        // 4. 重新渲染表格
        this.current = 1
        this.initData()
        // 5. 关闭drawer
        this.handleClose()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
